package com.leyou.item.service;

import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 岩冰
 * @version 1.0
 * @date:2018/9/25
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    public List<Category> queryByParentId(Long pid) {
        Category category=new Category();
        category.setParentId(pid);
        List<Category> list = categoryMapper.select(category);
        return list;
    }

    public void deleteById(Long id) throws Exception {
        //看节点下面还有没有子节点
        List<Category> list = this.queryByParentId(id);
        if (list == null || list.size() == 0) {
            //如果没有子元素才删
            categoryMapper.deleteByPrimaryKey(id);
        } else {
            throw new Exception("父组件不容许删除");
        }
    }

    public List<Category> queryByBrandId(Long bid) {

        return categoryMapper.queryByBrandId(bid);
    }

    public List<String> queryCategoryNames(List<Long> ids) {
        //查询category的name返回
        return categoryMapper.selectByIdList(ids).
                stream().map( Category::getName).collect(Collectors.toList());
    }

/*
    @Autowired
    private RedisTemplate redisTemplate;
*/

    /**
     * 先查缓存.没有的话再查数据库
     * @param id
     * @return
     */
    public List<Category> queryAllById3(Long id) {
        List<Category> categories = null;
//        categories = (List<Category>) redisTemplate.opsForHash().get("category", "queryAllById3");
//        if (categories==null) {
            Category c3 = this.categoryMapper.selectByPrimaryKey(id);
            Category c2 = this.categoryMapper.selectByPrimaryKey(c3.getParentId());
            Category c1 = this.categoryMapper.selectByPrimaryKey(c2.getParentId());
            categories = Arrays.asList(c1, c2, c3);
//            redisTemplate.opsForHash().put("category", "queryAllById3", categories);
//        }
        return categories;
    }
}
